package com.example.healthy_station_flutter.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.widget.Toast;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2023/12/26 13:56
 */

public class UsbPermissionReceiver extends BroadcastReceiver {
    public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbPermissionCallback usbPermissionCallback;
    public UsbPermissionReceiver(UsbPermissionCallback usbPermissionCallback){
        this.usbPermissionCallback = usbPermissionCallback;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    //user choose YES for your previously popup window asking for grant perssion for this usb device
                    if (null != usbDevice) {
                        usbPermissionCallback.result();
                    }
                } else {
                    //user choose NO for your previously popup window asking for grant perssion for this usb device
                    Toast.makeText(context, String.valueOf("Permission denied for device" + usbDevice), Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
